package com.app.service;

import com.app.datasource.DatabaseFactoryBean;
import com.app.datasource.DatasourceInfo;
import com.app.datasource.HikarDatasourceFactory;
import com.app.jvmdebug.ThreadDebug;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * jvm调优测试
 *
 * @author ch
 * @date 2023/1/6 17:42
 */
@Service
public class JvmDebugService {

    /**
     * 生成大量数据库连接
     */
    public void runLotDbConnection() throws SQLException {
        DatasourceInfo info = new DatasourceInfo();
        info.setId("1");
        info.setName("hikari");
        info.setUrl("jdbc:oracle:thin:@192.168.30.38:1521/XE");
        info.setDriverClassName("oracle.jdbc.OracleDriver");
        info.setUsername("chz");
        info.setPassword("11");
        DatabaseFactoryBean databaseFactoryBean = new HikarDatasourceFactory().createDatabaseFactoryBean(info);
        while (true) {
            DataSource dataSource = databaseFactoryBean.getDataSource();
            DataSourceUtils.getConnection(dataSource);
        }
    }

    /**
     * 大量线程
     */
    public void runLotThread() {
        int i = 1;
        while (true) {
            new ThreadDebug().start();
            System.out.println(i++);
        }
    }

    private int stackLength = 1;

    /**
     * 栈深异常
     */
    public void runDeepMethod() {
        try {
            jvmDebugMethod();
        } catch (Error e) {
            System.out.println("栈帧长度：" + stackLength);
            e.printStackTrace();
        }
    }

    private void jvmDebugMethod() {
        stackLength++;
        jvmDebugMethod();
    }

    /**
     * 模拟大量正常线程调用
     */
    public void runSleepMethod() {
        try {
            Thread.sleep(120000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
